package com.njbw.user.db;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.njbw.user.entity.po.SysUserPo;
import com.njbw.user.service.SysUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Log4j2
@Component
public class SysUserForwardHandler extends AbstractBackUpDataHandler<SysUserPo, SysUserBackUpDataRule> {

    /**
     * 归档规则，可以配合 nacos 动态配置
     * 实际上跟 BackUpDataRule 的属性是一一对应的，是一个 json
     */
    private String sysUserBackUpRuleStr;

    /**
     * 归档停止 flag，配合 nacos
     */
    private Boolean stopFlag;

    @Resource
    private SysUserService sysUserService;

    @Override
    public Boolean needStop() {
        return stopFlag;
    }

    @Override
    SysUserBackUpDataRule getRule() {
        SysUserBackUpDataRule backUpRule = JSON.parseObject(sysUserBackUpRuleStr, SysUserBackUpDataRule.class);
        Preconditions.checkNotNull(backUpRule, "归档规则不能为空！");
        Preconditions.checkNotNull(backUpRule.getQuerySize(), "查询数量不能为空！");
        Preconditions.checkNotNull(backUpRule.getBeginId(), "beginId 不能为空！");
        long endId = backUpRule.getBeginId() + backUpRule.getQuerySize();
        backUpRule.setEndId(endId);
        return backUpRule;
    }

    @Override
    public SysUserBackUpDataRule changeOffSet(SysUserBackUpDataRule backUpDataRule) {
        backUpDataRule.setBeginId(backUpDataRule.getEndId());
        Long endId = backUpDataRule.getBeginId() + backUpDataRule.getQuerySize();
        backUpDataRule.setEndId(endId);
        return backUpDataRule;
    }

    @Override
    public List<SysUserPo> queryData(SysUserBackUpDataRule backUpDataRule) {
        // 查询逻辑
        SysUserPo sysUserPo = new SysUserPo();
        return sysUserService.queryAll(sysUserPo);
    }

    @Override
    public void insertData(List<SysUserPo> dataList) {
        // 批量插入搭配 sysUserBack 表中
        sysUserService.saveBatch(dataList);
    }

    @Override
    public void deleteData(List<SysUserPo> dataList) {
        List<Long> ids = dataList.stream().map(SysUserPo::getId).collect(Collectors.toList());
        sysUserService.removeByIds(ids);
    }

    @Override
    public BackUpDataSceneEnum getScene() {
        return BackUpDataSceneEnum.USER_FORWARD;
    }
}
